<?php
// 调试阿里云千问API连接

function testQwenAPI() {
    // 阿里云千问API配置
    $apiKey = 'sk-416b931b781c420c9f6331b7346962b5';
    $apiUrl = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions';
    $model = 'qwen-plus';
    
    // 构造提示词
    $prompt = "请告诉我西红柿炒鸡蛋这道菜的制作方法，包括所需食材、烹饪时长和制作步骤。";
    
    $data = [
        'model' => $model,
        'messages' => [
            [
                'role' => 'user',
                'content' => $prompt
            ]
        ],
        'temperature' => 0.1,
        'max_tokens' => 1000
    ];
    
    // 发起HTTP请求
    $headers = [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json'
    ];
    
    echo "正在调用阿里云千问API...\n";
    echo "API地址: " . $apiUrl . "\n";
    echo "模型: " . $model . "\n";
    echo "提示词: " . $prompt . "\n\n";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    
    echo "HTTP状态码: " . $httpCode . "\n";
    echo "CURL错误: " . $error . "\n";
    echo "响应内容: " . $response . "\n\n";
    
    if ($response) {
        $responseArr = json_decode($response, true);
        if ($responseArr) {
            echo "解析后的响应:\n";
            print_r($responseArr);
        } else {
            echo "JSON解析失败\n";
        }
    }
    
    curl_close($ch);
}

// 执行测试
testQwenAPI();
?>